#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[])
{
    unsigned char buf1[376];
    unsigned char buf2[567];
    int n, i, j, k, m, s, r;
    int sync = 0;

    unsigned char code = 0x08;	// Numéro du multiplex à extraire 1->0x08, 2->0x10 
    if (argc == 2 && argv[1][0] == '2')
	code = 0x10;

    m = 0;
    n = read(0, buf1, 376);
    r = n;
    while (n > 0) {
	for (i = 0; i < 188; i++) {
	    if (buf1[i] == 0x47 && buf1[i + 188] == 0x47) {
// Synchro 0x47 
		memcpy(&buf2[m], &buf1[i + 1], 187);
		i += 188;
		m += 187;
		if (m >= 381) {
		    for (k = 0; k < 190; k++) {
			if (!sync) {
			    if (buf2[k] == 0xB8
				&& (buf2[k + 1] == 0x08
				    || buf2[k + 1] == 0x10
				    || buf2[k + 1] == 0x00)
				&& (buf2[k + 191] == 0x08
				    || buf2[k + 191] == 0x10
				    || buf2[k + 191] == 0x00))
				sync = 1;
			} else {
			    if (buf2[k] == 0x00 || buf2[k] == 0x08
				|| buf2[k] == 0x10) {
				if (buf2[k + 190] == 0x08
				    || buf2[k + 190] == 0x10
				    || buf2[k + 190] == 0x00) {
				    if (buf2[k] == code) {
					buf2[k + 2] = 0x47;
					write(1, &buf2[k + 2], 188);
				    }
				    k += 190;
				    break;
				} else if (buf2[k + 190] == 0xB8 &&
					   (buf2[k + 191] == 0x10
					    || buf2[k + 191] == 0x08
					    || buf2[k + 191] == 0x00)) {
				    if (buf2[k] == code) {
					buf2[k + 2] = 0x47;
					write(1, &buf2[k + 2], 188);
				    }
				    k += 191;
				    break;
				}
			    }
			}
		    }
		    for (s = k, j = 0; s < m; s++, j++)
			buf2[j] = buf2[s];
		    m -= k;
		}
		break;
	    }
	}
	j = 0;
	n = 376 - i;
	while (i < 376)
	    buf1[j++] = buf1[i++];
	n = read(0, &buf1[376 - n], n);
	r += n;
    }
    return EXIT_SUCCESS;
}
